package com.zm.xiaohashu.count.biz.consumer;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.nacos.shaded.com.google.common.util.concurrent.RateLimiter;
import com.zm.xiaohashu.count.biz.constant.MQConstants;
import com.zm.xiaohashu.count.biz.constant.RedisKeyConstants;
import com.zm.xiaohashu.count.biz.enums.FollowUnfollowTypeEnum;
import com.zm.xiaohashu.count.biz.model.dto.CountFollowUnfollowMqDTO;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.client.producer.SendCallback;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.stereotype.Component;

import java.util.Objects;

@Component
@RocketMQMessageListener(consumerGroup = "xiaohashu_group_" + MQConstants.TOPIC_COUNT_FOLLOWING, // Group 组
        topic = MQConstants.TOPIC_COUNT_FOLLOWING // 主题 Topic
)
@Slf4j
public class CountFollowingConsumer implements RocketMQListener<String> {
    // 每秒创建 5000 个令牌
    private RateLimiter rateLimiter = RateLimiter.create(5000);
    @Resource
    private RedisTemplate<String, Object> redisTemplate;
    @Resource
    private RocketMQTemplate rocketMQTemplate;

    @Override
    public void onMessage(String body) {
        if (StrUtil.isBlank(body)) return;
        log.info("## 消费到了 MQ 【计数: 关注数】, {}...", body);
        rateLimiter.acquire();
        CountFollowUnfollowMqDTO countFollowUnfollowMqDTO = JSONUtil.toBean(body, CountFollowUnfollowMqDTO.class);
        Integer type = countFollowUnfollowMqDTO.getType();
        Long userId = countFollowUnfollowMqDTO.getUserId();
        long total = Objects.equals(type, FollowUnfollowTypeEnum.FOLLOW.getCode()) ? 1 : -1;
        String userCountKey = RedisKeyConstants.buildCountUserKey(userId);
        Boolean isExist = redisTemplate.hasKey(userCountKey);
        if (isExist) {
            redisTemplate.opsForHash().increment(userCountKey, RedisKeyConstants.FIELD_FOLLOW_TOTAL, total);
        }
        //mq落库
        rocketMQTemplate.asyncSend(MQConstants.TOPIC_COUNT_FOLLOWING_2_DB, body, new SendCallback() {
            @Override
            public void onSuccess(SendResult sendResult) {

                log.info("==> 【计数服务：关注数入库】MQ 发送成功，SendResult: {}", sendResult);
            }

            @Override
            public void onException(Throwable throwable) {
                log.error("==> 【计数服务：关注数入库】MQ 发送异常: ", throwable);
            }
        });

    }

}
